/**
 * @date 2022/4/6
 * @description 路由权限控制
 * @author 
 */

import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { setting } from '@/config/setting'
import { getPageTitle } from '@/utils/common'
import { resetMessage } from '@/utils/resetMessage.js'

const { progressBar, routesWhiteList, recordRoute } = setting

NProgress.configure({
    easing: 'ease',
    speed: 500,
    trickleSpeed: 200,
    showSpinner: false,
})
router.beforeEach(async(to, from, next) => {
    if (progressBar) NProgress.start()

    let hasToken = store.getters['user/token']
    if (hasToken) {
        //token存在
        if (to.path === '/login') {
            next('/')
            if (progressBar) NProgress.done()
        } else {
            const hasMenuList = store.getters['user/menuList'] && store.getters['user/menuList'].length > 0
            if (hasMenuList) {
                next()
            } else {
                try {
                    let menuList
                    menuList = await store.dispatch('user/getMenuList')
                    await store.dispatch('routes/setAllRoutes').then((res) => {
                        res.forEach((item) => {
                            router.addRoute(item)
                        })
                        store.dispatch('user/getUserInfo')
                        next({...to, replace: true })
                    })
                } catch {
                    console.log('进入错误了吗')
                        // ElMessage({
                        //     message: '暂无权限，不能进入',
                        //     type: 'error',
                        // })
                    resetMessage.error('暂无权限，无法进入')
                    await store.dispatch('user/resetToken')
                    if (progressBar) NProgress.done()
                }
            }
        }
    } else {
        console.log('免登录路由')
            // 免登录路由
        if (routesWhiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            if (recordRoute) {
                next(`/login?redirect=${to.path}`)
            } else {
                next('/login')
            }
            if (progressBar) NProgress.done()
        }
    }
    document.title = getPageTitle(to.meta.title)
})

router.afterEach(() => {
    if (progressBar) NProgress.done()
})